<template>
  <div class="">
    <el-card class="main tl">
      <codemirror :value="code ? code :defaultCode" :options="cmOptions"  ref="oneLineCodeMirrors"/>
    </el-card>
  </div>
</template>

<script>
import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css' 
import 'codemirror/lib/codemirror.css'
import "codemirror/theme/ayu-dark.css";
require("codemirror/mode/javascript/javascript")

export default {
  name: 'hzjmain',
  props: {
    msg: String,
    code:String
  },
  components: {
    codemirror
  },
  data() {
    return { 
      cmOptions:{
          value:'',
          mode:"text/javascript",
          theme: "ayu-dark",
          readOnly:true,
      },
      defaultCode:`importFile(file, fileList) {
              const fileReader = new FileReader();
              fileReader.onload = ev => {
                  try {
                  const data = ev.target.result;
                  const workbook = XLSX.read(data, {
                      type: "binary"
                  });
                  //处理导入的表的数据  *************************************start***********************
                  let sheet = Object.keys(workbook.Sheets)[0];
                  let json = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]); //获得以第一列为键名的sheet数组对象
                  this.dataList=json
                  for(let attr in json[0]){
                      this.dataFirst.push(attr)
                  }
                  //处理导入的表的数据  *************************************end***********************
              
                  } catch (e) {
                  console.log(e);
                  }
              };
              fileReader.readAsBinaryString(file.raw);
            },
            exportXlsx() {
              //处理导出的表的数据  *************************************start***********************
              let obj = {
                  sheet1: [this.dataFirst]
              };
              

              for (let item of this.dataList) {
                  let row = []
                  for(let index of this.dataFirst){
                  row.push(item[index])
                  }
                  obj["sheet1"].push(row);
              }
              //处理导出的表的数据  *************************************end***********************
              this.downloadXlsx(obj, "陀螺仪", "信息表");
              },
              downloadXlsx(data, fileName, sheetName) {
              fileName = (fileName || "fileName") + ".xlsx";
              sheetName = sheetName || "sheet1";
              download(data2blob(data, sheetName), fileName);

              //   下载excel文件
              function download(url, fileName) {
                  if (typeof url == "object" && url instanceof Blob) {
                  url = URL.createObjectURL(url); // 创建blob地址
                  }
                  let element = document.createElement("a");
                  element.href = url;
                  element.download = fileName; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
                  element.style.display = "none";
                  element.click();
              }
              // 利用xlsx提供的方法将对象转成blob
              function data2blob(data, sheetName) {
                  let workbook = {
                  SheetNames: [],
                  Sheets: {}
                  };
                  if (data instanceof Array) {
                  workbook.SheetNames = [sheetName];
                  workbook.Sheets[sheetName] = XLSX.utils.aoa_to_sheet(data);
                  } else if (data instanceof Object) {
                  for (const key in data) {
                      if (Object.prototype.hasOwnProperty.call(data, key)) {
                      const arr = data[key];
                      if (arr instanceof Array) {
                          workbook.SheetNames.push(key);
                          workbook.Sheets[key] = XLSX.utils.aoa_to_sheet(arr);
                      } else throw new Error("数据格式不正确");
                      }
                  }
                  }
                  // 生成excel的配置项
                  let wopts = {
                  bookType: "xlsx", // 要生成的文件类型
                  bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
                  type: "binary"
                  };
                  let wbout = XLSX.write(workbook, wopts);
                  let blob = new Blob([s2ab(wbout)], {
                  type: "application/octet-stream"
                  });
                  // 字符串转ArrayBuffer
                  function s2ab(s) {
                  let buf = new ArrayBuffer(s.length);
                  let view = new Uint8Array(buf);
                  for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
                  return buf;
                  }
                  return blob;
              }
            }`
    }
  },
  created(){
    if(!this.code){
      this.getDefaultCode()
    }
  },
  methods:{
      getDefaultCode(){
        this.code=`importFile(file, fileList) {
              const fileReader = new FileReader();
              fileReader.onload = ev => {
                  try {
                  const data = ev.target.result;
                  const workbook = XLSX.read(data, {
                      type: "binary"
                  });
                  //处理导入的表的数据  *************************************start***********************
                  let sheet = Object.keys(workbook.Sheets)[0];
                  let json = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]); //获得以第一列为键名的sheet数组对象
                  this.dataList=json
                  for(let attr in json[0]){
                      this.dataFirst.push(attr)
                  }
                  //处理导入的表的数据  *************************************end***********************
              
                  } catch (e) {
                  console.log(e);
                  }
              };
              fileReader.readAsBinaryString(file.raw);
            },
            exportXlsx() {
              //处理导出的表的数据  *************************************start***********************
              let obj = {
                  sheet1: [this.dataFirst]
              };
              

              for (let item of this.dataList) {
                  let row = []
                  for(let index of this.dataFirst){
                  row.push(item[index])
                  }
                  obj["sheet1"].push(row);
              }
              //处理导出的表的数据  *************************************end***********************
              this.downloadXlsx(obj, "陀螺仪", "信息表");
              },
              downloadXlsx(data, fileName, sheetName) {
              fileName = (fileName || "fileName") + ".xlsx";
              sheetName = sheetName || "sheet1";
              download(data2blob(data, sheetName), fileName);

              //   下载excel文件
              function download(url, fileName) {
                  if (typeof url == "object" && url instanceof Blob) {
                  url = URL.createObjectURL(url); // 创建blob地址
                  }
                  let element = document.createElement("a");
                  element.href = url;
                  element.download = fileName; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
                  element.style.display = "none";
                  element.click();
              }
              // 利用xlsx提供的方法将对象转成blob
              function data2blob(data, sheetName) {
                  let workbook = {
                  SheetNames: [],
                  Sheets: {}
                  };
                  if (data instanceof Array) {
                  workbook.SheetNames = [sheetName];
                  workbook.Sheets[sheetName] = XLSX.utils.aoa_to_sheet(data);
                  } else if (data instanceof Object) {
                  for (const key in data) {
                      if (Object.prototype.hasOwnProperty.call(data, key)) {
                      const arr = data[key];
                      if (arr instanceof Array) {
                          workbook.SheetNames.push(key);
                          workbook.Sheets[key] = XLSX.utils.aoa_to_sheet(arr);
                      } else throw new Error("数据格式不正确");
                      }
                  }
                  }
                  // 生成excel的配置项
                  let wopts = {
                  bookType: "xlsx", // 要生成的文件类型
                  bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
                  type: "binary"
                  };
                  let wbout = XLSX.write(workbook, wopts);
                  let blob = new Blob([s2ab(wbout)], {
                  type: "application/octet-stream"
                  });
                  // 字符串转ArrayBuffer
                  function s2ab(s) {
                  let buf = new ArrayBuffer(s.length);
                  let view = new Uint8Array(buf);
                  for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
                  return buf;
                  }
                  return blob;
              }
            }`
      }

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style >
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
.CodeMirror {
  border: 1px solid #eee;
  min-height: 800px;
}
</style>
